﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace WebAuthentication
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 每个aspx页面要求认证时被触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpContext _ctx = HttpContext.Current;
            if (_ctx.User != null)
            {
                // 认证成功的用户，才进行授权处理
                if (_ctx.User.Identity.IsAuthenticated)
                {
                    FormsIdentity _Identity = (FormsIdentity)_ctx.User.Identity;
                    // 将角色字符串,即login.aspx.cs中的“管理员,会员”,变成数组
                    string[] Roles = _Identity.Ticket.UserData.Split(',');
                    // 将带有角色的信息，重新生成一个GenericPrincipal赋值给User，相当于winform中的Thread.CurrentPrincipal = _principal
                    _ctx.User = new GenericPrincipal(_Identity, Roles); 
                }
            }
        }
    }
}